import React, { useState, useEffect } from 'react';
import { Select, DatePicker, Table, Button, Space, Image, Card, Steps, Modal, Form, Input, message } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import styles from './orderManager.module.css';
import { _apiOrderList, _apiOrderDetail, _apiOrderUpdate } from '../../../api/index';

const { RangePicker } = DatePicker;

const OrderManager = () => {
  // 添加当前选中的tab状态
  const [activeTab, setActiveTab] = useState('all');
  // 添加显示详情的状态
  const [showDetail, setShowDetail] = useState(false);
  // 当前选中的订单
  const [currentOrder, setCurrentOrder] = useState(null);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [isRemarkModalVisible, setIsRemarkModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [remarkForm] = Form.useForm();
  const [dataSource, setDataSource] = useState([]);
  const [loading, setLoading] = useState(false);
  // 添加分页和日期范围状态
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [dateRange, setDateRange] = useState(null);
  const [orderDetailData, setOrderDetailData] = useState(null);

  // 订单状态选项
  const orderStatusOptions = [
    { value: 'all', label: '全部订单' },
    { value: '1', label: '等待付款' },
    { value: '2', label: '待付尾款' },
    { value: '3', label: '拼团中' },
    { value: '4', label: '待发货' },
    { value: '5', label: '待收货' },
    { value: '6', label: '已签收' },
    { value: '7', label: '完成' },
    { value: '8', label: '取消(客户)' },
    { value: '9', label: '作废(系统)' }
  ];

  // 订单详情页的Steps配置
  const steps = [
    { title: '买家下单', description: '2024.12.01' },
    { title: '洗鞋中' },
    { title: '配送中', status: 'process' },
    { title: '已完成' },
    { title: '售后中' }
  ];

  // 商品详情表格列配置
  const detailColumns = [
    {
      title: '商品信息',
      dataIndex: 'goodsInfo',
      render: (text, record) => (
        <div className={styles.productInfo}>
          <Image width={80} src={record.imgUrl} />
          <div>
            <div>{record.goodsTitle}</div>
            <div>规格: {record.skuText || '默认'}</div>
          </div>
        </div>
      ),
    },
    {
      title: '单价（元）',
      dataIndex: 'realPrice',
      align: 'center',
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      align: 'center',
    },
    {
      title: '实付金额（元）',
      dataIndex: 'realAmount',
      align: 'center',
      render: (_, record) => {
        return (record.realPrice * record.quantity).toFixed(2);
      }
    }
  ];

  // 表格列定义
  const columns = [
    {
      title: '商品信息',
      dataIndex: 'product',
      render: (product) => (
        <div className={styles.productInfo}>
          <Image width={80} src={product.image} />
          <div>
            <div>{product.name}</div>
            <div>单价: ¥{product.price} 数量: {product.quantity}</div>
          </div>
        </div>
      ),
    },
    {
      title: '会员信息',
      dataIndex: 'member',
      render: (member) => (
        <div className={styles.memberInfo}>
          <Image width={40} src={member.avatar} className={styles.avatar} />
          <div>
            <div>{member.name}</div>
            <div>{member.phone}</div>
          </div>
        </div>
      ),
    },
    {
      title: '订单状态',
      dataIndex: 'status',
    },
    {
      title: '订单编号',
      dataIndex: 'orderNumber',
    },
    {
      title: '下单时间',
      dataIndex: 'orderTime',
    },
    {
      title: '共计（元）',
      dataIndex: 'total',
    },
    {
      title: '操作',
      render: (_, record) => (
        <Button 
          type="link" 
          onClick={() => {
            setCurrentOrder(record);
            handleViewDetail(record.key);
            setShowDetail(true);
          }}
        >
          订单详情
        </Button>
      ),
    },
  ];

  // 修改订单状态映射函数
  const getOrderStatus = (status) => {
    const statusMap = {
      1: '等待付款',
      2: '待付尾款',
      3: '拼团中',
      4: '待发货',
      5: '待收货',
      6: '已签收',
      7: '完成',
      8: '取消(客户)',
      9: '作废(系统)'
    };
    return statusMap[status] || '未知状态';
  };

  // 添加支付方式判断函数
  const getPaymentMethod = (paymentId) => {
    switch (paymentId) {
      case 1:
        return '余额支付';
      case 2:
        return '微信支付';
      case 3:
        return '支付宝支付';
      default:
        return '未知';
    }
  };

  // 获取订单列表数据
  const fetchOrderList = async () => {
    try {
      setLoading(true);
      
      // 构建请求参数
      const params = {
        status: activeTab === 'all' ? undefined : activeTab, // 如果是 'all' 则不传 status 参数
        pageSize: pagination.pageSize,
        pageNum: pagination.current
      };

      // 如果有日期范围，添加日期参数
      if (dateRange && dateRange[0] && dateRange[1]) {
        params.startTime = dateRange[0].format('YYYY-MM-DD');
        params.endTime = dateRange[1].format('YYYY-MM-DD');
      }

      // 移除所有 undefined 和 null 的参数
      const cleanParams = Object.fromEntries(
        Object.entries(params).filter(([_, value]) => value != null)
      );
      
      console.log('发送的请求参数:', cleanParams);
      
      const response = await _apiOrderList(cleanParams);
      console.log('API response:', response); // 添加日志查看数据

      if (response?.data) {
        const formattedData = response.data.map(item => ({
          key: item.id,
          product: {
            image: '',
            name: `订单 ${item.orderNo}`,
            price: 0,
            quantity: 1
          },
          member: {
            avatar: '',
            name: item.userName,
            phone: ''
          },
          status: getOrderStatus(item.status),
          orderNumber: item.orderNo,
          orderTime: item.addTime,
          total: item.realAmount || 0
        }));

        console.log('Formatted data:', formattedData); // 添加日志查看转换后的数据
        setDataSource(formattedData);
        setPagination({
          ...pagination,
          total: response.data.length
        });
      } else {
        message.error(response?.message || '获取订单列表失败');
      }
    } catch (error) {
      console.error('请求错误:', error);
      message.error('获取订单列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 在组件加载时获取数据
  useEffect(() => {
    fetchOrderList();
  }, [activeTab]); // 当 activeTab 改变时重新获取数据

  // 修改搜索按钮的点击处理函数
  const handleSearch = () => {
    setPagination(prev => ({ ...prev, current: 1 })); // 重置到第一页
    fetchOrderList();
  };

  // 修改表格分页变化处理函数
  const handleTableChange = (newPagination) => {
    setPagination(newPagination);
    fetchOrderList();
  };

  // 添加获取订单详情的函数
  const handleViewDetail = async (id) => {
    try {
      const response = await _apiOrderDetail({ id });
      console.log('订单详情原始数据:', response);
      
      if (response?.data) {
        setOrderDetailData(response.data);
     
      } else {
        message.error('获取订单详情失败');
      }
    } catch (error) {
      console.error('获取订单详情失败:', error);
      message.error('获取订单详情失败');
    }
  };

  // 渲染订单详情页
  const renderOrderDetail = () => {
    if (!currentOrder) return null;

    return (
      <div className={styles.container}>
        <div className={styles.header}>
          <div className={styles.breadcrumb}>
            <h2>当前位置：订单管理 {'>'}订单详情</h2>
            <Button type="link" onClick={() => setShowDetail(false)}>返回</Button>
          </div>
        </div>

        <Card className={styles.progressCard}>
          <div className={styles.orderStatus}>配送中</div>
          <Steps current={2} items={steps} className={styles.steps} />
          <div className={styles.orderDate}>2024.12.01</div>
        </Card>

        <div className={styles.infoSection}>
          <Card title="收货人信息" extra={<Button type="link" onClick={() => setIsEditModalVisible(true)}>编辑</Button>}>
            <div className={styles.infoItem}>
              <span>收货人姓名：</span>{orderDetailData?.orderAddress?.[0]?.acceptName || '暂无'}
            </div>
            <div className={styles.infoItem}>
              <span>联系电话：</span>{orderDetailData?.orderAddress?.[0]?.mobile || '暂无'}
            </div>
            <div className={styles.infoItem}>
              <span>收货地址：</span>{orderDetailData?.orderAddress?.[0]?.address || '暂无'}
            </div>
          </Card>

          <Card title="订单信息">
            <div className={styles.infoItem}>
              <span>订单编号：</span>{orderDetailData?.orderNo}
            </div>
            <div className={styles.infoItem}>
              <span>下单时间：</span>{orderDetailData?.addTime}
            </div>
            <div className={styles.infoItem}>
              <span>支付时间：</span>{orderDetailData?.completeTime}
            </div>
            <div className={styles.infoItem}>
              <span>支付方式：</span>
              {getPaymentMethod(orderDetailData?.orderRelations?.[0]?.orderPayment?.paymentId)}
            </div>
            <div className={styles.infoItem}>
              <span>订单备注：</span>{orderDetailData?.postscript}
              <Button type="link" onClick={() => setIsRemarkModalVisible(true)}>编辑</Button>
            </div>
          </Card>
        </div>

        <Card title="商品信息" className={styles.productCard}>
          <Table 
            columns={detailColumns} 
            dataSource={orderDetailData?.orderGoods || []}
            pagination={false}
            rowKey="id"
            footer={() => (
              <div className={styles.orderSummary}>
                <div>本单积分：{orderDetailData?.point}积分</div>
                <div>
                  <div>商品总价：{orderDetailData?.orderAmount}元</div>
                  <div>优惠：{orderDetailData?.promotionAmount}元</div>
                  <div>实收金额：{orderDetailData?.realAmount}元</div>
                </div>
              </div>
            )}
          />
        </Card>
      </div>
    );
  };

  // 处理编辑表单提交
  const handleEditSubmit = async (values) => {
    try {
      const params = {
        id: currentOrder.key,
        acceptName: values.name,
        mobile: values.phone,
        address: values.address
      };

      const response = await _apiOrderUpdate(params);
      
      if (response?.code === 200) {
        message.success('更新成功');
        setIsEditModalVisible(false);
        // 重新获取订单详情以更新显示
        handleViewDetail(currentOrder.key);
      } else {
        message.error(response?.message || '更新失败');
      }
    } catch (error) {
      console.error('更新失败:', error);
      message.error('更新失败');
    }
  };

  // 编辑弹窗
  const renderEditModal = () => (
    <Modal
      title="编辑收货人信息"
      open={isEditModalVisible}
      onOk={() => form.submit()}
      onCancel={() => setIsEditModalVisible(false)}
      okText="确认"
      cancelText="取消"
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleEditSubmit}
        initialValues={{
          name: orderDetailData?.orderAddress?.[0]?.acceptName || '',
          phone: orderDetailData?.orderAddress?.[0]?.mobile || '',
          address: orderDetailData?.orderAddress?.[0]?.address || ''
        }}
      >
        <Form.Item
          label="收货人姓名"
          name="name"
          rules={[{ required: true, message: '请输入收货人姓名' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="联系电话"
          name="phone"
          rules={[{ required: true, message: '请输入联系电话' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="收货地址"
          name="address"
          rules={[{ required: true, message: '请输入收货地址' }]}
        >
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );

  // 处理备注编辑表单提交
  const handleRemarkSubmit = (values) => {
    console.log('备注的值:', values);
    setIsRemarkModalVisible(false);
  };

  // 备注编辑弹窗
  const renderRemarkModal = () => (
    <Modal
      title="编辑订单备注"
      open={isRemarkModalVisible}
      onOk={() => remarkForm.submit()}
      onCancel={() => setIsRemarkModalVisible(false)}
      okText="确认"
      cancelText="取消"
    >
      <Form
        form={remarkForm}
        layout="vertical"
        onFinish={handleRemarkSubmit}
        initialValues={{
          remark: ''
        }}
      >
        <Form.Item
          label="订单备注"
          name="remark"
        >
          <Input.TextArea rows={4} />
        </Form.Item>
      </Form>
    </Modal>
  );

  // 主渲染函数
  return (
    <>
      {showDetail ? renderOrderDetail() : (
        <div className={styles.container}>
          <div className={styles.header}>
            <h2>当前位置：订单管理</h2>
          </div>
          
          <div className={styles.filterSection}>
            <Space size="large">
              <div>
                <span>订单状态：</span>
                <Select
                  value={activeTab}
                  style={{ width: 200 }}
                  options={orderStatusOptions}
                  onChange={(value) => setActiveTab(value)}
                />
              </div>
              <div>
                <span>下单日期：</span>
                <RangePicker value={dateRange} onChange={setDateRange} />
              </div>
              <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                搜索
              </Button>
            </Space>
          </div>

          <div className={styles.tabSection}>
            {orderStatusOptions.map(option => (
              <span 
                key={option.value}
                className={`${styles.tabItem} ${activeTab === option.value ? styles.activeTab : ''}`}
                onClick={() => setActiveTab(option.value)}
              >
                {option.label}
              </span>
            ))}
          </div>

          <Table 
            loading={loading}
            columns={columns} 
            dataSource={dataSource}
            pagination={pagination}
            onChange={handleTableChange}
          />
        </div>
      )}
      {renderEditModal()}
      {renderRemarkModal()}
    </>
  );
};

export default OrderManager;
